package zhishu.iceyyy.com.bxq_2500.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import zhishu.iceyyy.com.bxq_2500.R;
import zhishu.iceyyy.com.bxq_2500.api.API;
import zhishu.iceyyy.com.bxq_2500.api.Okhttp;
import zhishu.iceyyy.com.bxq_2500.base.ALL_CONFIG;
import zhishu.iceyyy.com.bxq_2500.bean.MyEvent;
import zhishu.iceyyy.com.bxq_2500.bean.Version;
import zhishu.iceyyy.com.bxq_2500.fragment.My_Fragment;
import zhishu.iceyyy.com.bxq_2500.fragment.OneFragment;
import zhishu.iceyyy.com.bxq_2500.fragment.Share_Fragment;
import zhishu.iceyyy.com.bxq_2500.fragment.Zhi_Fragment;
import zhishu.iceyyy.com.bxq_2500.services.UpdateService;
import zhishu.iceyyy.com.bxq_2500.utils.JSONUtils;


public class MainActivity extends FragmentActivity {

    AlertDialog.Builder alert;
    // 定义FragmentTabHost对象
    private FragmentTabHost mTabHost;
    // 定义一个布局
    private LayoutInflater layoutInflater;
    Timer timer = new Timer();
    private Class[] fragmentArray = null;
    private int[] mImageViewArray = null;
    private String[] mTextviewArray = null;
    private static Boolean isQuit = false;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintab);
        EventBus.getDefault().register(this);
        try {
            //本地版本号
            version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        initView();


    }


    public void onEventMainThread(MyEvent event) {
        if (!TextUtils.isEmpty(event.getContent()) && event.getContent().equals("finish")) {
            finish();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化组件
     */
    private void initView() {
        // 实例化布局对象
        layoutInflater = LayoutInflater.from(this);
        // 实例化TabHost对象，得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null);
        fragmentArray = new Class[]{OneFragment.class, Zhi_Fragment.class, Zhi_Fragment.class, Share_Fragment.class, My_Fragment.class};
        //定义数组来存放按钮图片
        mImageViewArray =
                new int[]{R.drawable.tab_sp_btn, R.drawable.tab_sy_btn, R.drawable.tab_sy_btn, R.drawable.tab_fx_btn, R.drawable.tab_tk_btn
                };
        //Tab选项卡的文字
        mTextviewArray = new String[]{"视频", "小说", "漫画", "分享", "我的"};

        // 得到fragment的个数
        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            // 为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
                    .setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            // 设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i)
                    .setBackgroundResource(R.color.white);
        }


    }


    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_1_view, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);

        return view;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isQuit == false) {
                isQuit = true;
                Toast.makeText(getBaseContext(), "再按一次返回键退出程序",
                        Toast.LENGTH_SHORT).show();
                TimerTask task = null;
                task = new TimerTask() {
                    public void run() {
                        isQuit = false;
                    }
                };
                timer.schedule(task, 2000);
            } else {

                finish();

            }
        }
        return false;
    }

    int version;

    public void checkVersion(final int Updateversion, final String url) {
        http:
//119.29.218.203:20771/file/app-release.apk
        if (version < Updateversion) {
            //发现新版本，提示用户更新
            android.support.v7.app.AlertDialog.Builder alert = new android.support.v7.app.AlertDialog.Builder(this);
            alert.setTitle("软件升级")
                    .setMessage("发现新版本,建议立即更新使用.")
                    .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //开启更新服务UpdateService
                            //这里为了把update更好模块化，可以传一些updateService依赖的值
                            //如布局ID，资源ID，动态获取的标题,这里以app_name为例
                            if (!TextUtils.isEmpty(url)) {
                                ALL_CONFIG.URL = url;
                                Intent updateIntent = new Intent(MainActivity.this, UpdateService.class);
                                updateIntent.putExtra("titleId", R.string.app_name);
                                startService(updateIntent);
                            }

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alert.create().show();
        } else {
            //清理工作，略去
            cheanUpdateFile(); //,文章后面我会附上代码
        }
    }

    private void cheanUpdateFile() {
        File updateFile = new File(Environment.getExternalStorageDirectory(), ALL_CONFIG.downloadDir + getResources().getString(R.string.app_name) + ".apk");
        if (updateFile.exists()) {
            //当不需要的时候，清除之前的下载文件，避免浪费用户空间
            updateFile.delete();
        }
    }
}
